import { Context } from "egg";
import helper from "../helper";

export default function authMiddleware() {
  return async (ctx: Context, next: () => Promise<any>) => {
    const url = ctx.request.url;

    if (url.indexOf("auth-api") >= 0) {
      const jwtKey = ctx.app.config.jwt.secret_key;

      let jwtToken = ctx.cookies.get(jwtKey);
      if (!!jwtToken === false) {
        jwtToken = ctx.get(jwtKey);
      }

      if (!!jwtToken === false) {
        jwtToken = ctx.request.query[jwtKey];
      }

      if (!!jwtToken === false) {
        jwtToken = ctx.request.body[jwtKey];
      }

      if (!!jwtToken === false) {
        jwtToken = ctx.get("");
      }

      if (!!jwtToken === false) {
        ctx.body = helper.fail("Unauthorized");
        ctx.status = 401;
      } else {
        try {
          const result = ctx.app.jwt.verify(jwtToken, ctx.app.config.jwt.secret);
          if (result) {
            await next();
          } else {
            ctx.body = helper.fail("Unauthorized");
            ctx.status = 401;
          }
        } catch (error) {
          ctx.body = helper.fail("Unauthorized");
          ctx.status = 401;
        }
      }
    } else {
      await next();
    }
  };
}
